﻿using AutoMapper;
using MediatR;
using MySqlX.XDevAPI.Common;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.BasicInformation.Departments;

namespace Enterprise_Set.API.Application.Commands.Week1.BusinessEntities
{
    /// <summary>
    /// 企业添加
    /// </summary>
    public class EnterpriseCreateHandler : IRequestHandler<EnterpriseCreareCommand, THE_WIND_RISES.Common.Dtos.Result>
    {
        /// <summary>
        /// 企业仓储
        /// </summary>
        private readonly IBaseRepository<Enterprise> enterpriseRepository;
        /// <summary>
        /// 自动映射
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="enterpriseRepository"></param>
        /// <param name="mapper"></param>
        public EnterpriseCreateHandler(IBaseRepository<Enterprise> enterpriseRepository, IMapper mapper)
        {
            this.enterpriseRepository = enterpriseRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<THE_WIND_RISES.Common.Dtos.Result> Handle(EnterpriseCreareCommand request, CancellationToken cancellationToken)
        {
            var result = new THE_WIND_RISES.Common.Dtos.Result() { Code = (int)CommonErrorCodes.Added };

            try
            {
                var AddData = mapper.Map<Enterprise>(request);

                string sql = "insert into Enterprise values(@EnterpriseId,@EnterpriseName,@EnterpriseAbbreviation,@Address,@LegalRepresentative,@Phone,@Email,@EstablishmentDate,@UpdDateTime,@PId,@IsDelete)";
                var AddNum = enterpriseRepository.Add(sql, AddData);


                if (AddNum > 0)
                {
                    result.Code = (int)CommonErrorCodes.Success;
                    return result;
                }
                else
                {
                    return result;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
